//
//  EbookBaseController.swift
//  eBooks
//
//  Created by JunMing on 2020/1/16.
//  Copyright © 2020 赵俊明. All rights reserved.
//

import UIKit
import FolioReaderKit
import Alamofire

class EbookBaseController: UIViewController,EbookBuyProtocol {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
    }
    
    deinit {
        print("‼️‼️‼️类\(self.className())已经释放")
    }
    
    func changeDataSource(_ model:Model,_ delete:Bool = false) { }
    
    func openEpubBooks(_ model:Model) {
        let config:FolioReaderConfig = FolioReaderConfig()
        config.tintColor = UIColor.gray
        config.menuTextColor = UIColor.gray
        let reader = FolioReader()
        reader.model = model
        reader.delegate = self
        reader.presentReader(parentViewController: self, withEpubPath: model.localPath(), andConfig: config)
    }
    
    /// 激励视频广告
    // Based_01:ca-app-pub-5649482177498836/8074840451
    func createRewardAD() {
        MobClick.event("epub_read_video_AD")
        let rewardedAd = GADRewardedAd(adUnitID: "ca-app-pub-5649482177498836/8074840451")
        rewardedAd.load(GADRequest()) { error in
            if let error = error {
                print("Loading failed: \(error)")
            } else {
                print("Loading Succeeded")
            }
        }

        let deadLine = DispatchTime.now()+2
        DispatchQueue.global().asyncAfter(deadline: deadLine) {
            if rewardedAd.isReady {
                rewardedAd.present(fromRootViewController: self, delegate: self)
            }
        }
    }
    
    /// 插页广告
    // interstitial:ca-app-pub-5649482177498836/1701003797
    func createItnterstitialAD() {
        MobClick.event("epub_read_insertPage_AD")
        let interstitial = GADInterstitial(adUnitID: "ca-app-pub-5649482177498836/1701003797")
        interstitial.load(GADRequest())
        interstitial.delegate = self
        let deadline = DispatchTime.now()+2
        DispatchQueue.global().asyncAfter(deadline: deadline) {
            if interstitial.isReady {
                interstitial.present(fromRootViewController: self)
            }
        }
    }
}

extension EbookBaseController:FolioReaderDelegate {
    func folioReader(_ folioReader: FolioReader, didFinishedLoading book: FRBook) {
        print("name:\(book.name ?? "nil"),title:\(book.authorName ?? "nil")")
        print("title:\(book.title ?? "nil"),duration:\(book.duration ?? "nil")")
    }
    
    func folioReaderDidClose(_ folioReader: FolioReader) {
        // 精确到秒
        if let newModel = folioReader.model {
            let model = newModel as! Model
            model.totalTime += folioReader.nowTotalTime
            model.readRate = String(format: "%.0f", arguments: [folioReader.readRate])
            SQLHelper.share.updateLocalDB(model, type: .totalTime)
        }
    }
    
    func folioReaderOpenError(_ folioReader: FolioReader, didFinishedLoading book: FRBook) {
        print("open error!!!😔😔😔")
        let sure = AlertItem(title: "知道了", icon: nil)
        let item = SheetItem(title: "发生错误")
        item.subTitle = "资源文件损坏导致打开错误😔，已删除错误文件"
        item.className = "BookInfoAlert"
        item.models = [sure]
        DispatchQueue.main.async {
            let manager = SheetManager(superView: nil, item: item)
            item.sheetType = .right
            manager.update()
            if let newModel = folioReader.model {
                let model = newModel as! Model
                FileHelper.deleteFile(model.fullname)
                model.isdel = true
                SQLHelper.share.updateLocalDB(model, type: .isDel)
                self.changeDataSource(model,true)
            }
        }
    }
    
    func folioReaderPageChange(_ readerCenter: FolioReaderCenter, _ page: Int) {
        if !Tools.getVip() {
            if page > 0 {
                readerCenter.createItnterstitialAD()
            }else {
                readerCenter.createRewardAD()
            }
        }
    }
    
    func pageViewDidLoad(_ readerCenter:FolioReaderCenter) {
        if !Tools.getVip() {
            readerCenter.createBannerAD()
        }
    }
}

// MARK: -- 谷歌广告 GoogleMobileAds 
import GoogleMobileAds
// addbanner:ca-app-pub-5649482177498836/1892575484
extension FolioReaderCenter {
    /// 横幅广告
    func createBannerAD() {
        if isExist() { return }
        MobClick.event("epub_read_bottom_AD")
        let adView = GADBannerView(adSize: kGADAdSizeBanner)
        adView.translatesAutoresizingMaskIntoConstraints = false
        adView.delegate = self
        adView.rootViewController = self
        adView.adUnitID = "ca-app-pub-5649482177498836/1892575484"
        adView.load(GADRequest())
        view.addSubview(adView)
        adView.snp.makeConstraints { (make) in
            make.left.right.equalTo(view)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-20)
            }else{
                make.bottom.equalTo(view.snp_bottom).offset(-20)
            }
        }
    }
    
    /// 插页广告
    // interstitial:ca-app-pub-5649482177498836/1701003797
    func createItnterstitialAD() {
        MobClick.event("epub_read_insertPage_AD")
        let interstitial = GADInterstitial(adUnitID: "ca-app-pub-5649482177498836/1701003797")
        interstitial.load(GADRequest())
        interstitial.delegate = self
        let deadline = DispatchTime.now()+2
        DispatchQueue.global().asyncAfter(deadline: deadline) {
            if interstitial.isReady {
                interstitial.present(fromRootViewController: self)
            }
        }
    }
    
    /// 激励视频广告
    // Based_01:ca-app-pub-5649482177498836/8074840451
    func createRewardAD() {
        MobClick.event("epub_read_video_AD")
        let rewardedAd = GADRewardedAd(adUnitID: "ca-app-pub-5649482177498836/8074840451")
        rewardedAd.load(GADRequest()) { error in
            if let error = error {
                print("Loading failed: \(error)")
            } else {
                print("Loading Succeeded")
            }
        }
        
        let deadLine = DispatchTime.now()+2
        DispatchQueue.global().asyncAfter(deadline: deadLine) {
            if rewardedAd.isReady {
                rewardedAd.present(fromRootViewController: self, delegate: self)
            }
        }
    }
    
    func isExist() -> Bool {
        var isExist = false
        for view in view.subviews {
            if view is GADBannerView {
                isExist = true
                break
            }
        }
        return isExist
    }
}
// MARK: GADInterstitialDelegate
extension FolioReaderCenter:GADInterstitialDelegate,GADBannerViewDelegate,GADRewardedAdDelegate {
    public func interstitialDidReceiveAd(_ ad: GADInterstitial) {
        print("interstitialDidReceiveAd")
        MobClick.event("google_ad_success")
    }
    
    public func interstitial(_ ad: GADInterstitial, didFailToReceiveAdWithError error: GADRequestError) {
        print("interstitialDidDismissScreen")
        MobClick.event("google_ad_fail")
    }
    
    public func interstitialDidDismissScreen(_ ad: GADInterstitial) {
        print("adViewDidReceiveAd")
    }
    
    public func interstitialWillPresentScreen(_ ad: GADInterstitial) {
        print("interstitialWillPresentScreen")
    }
    
    // MARK: GADBannerViewDelegate
    public func adViewDidReceiveAd(_ bannerView: GADBannerView) {
        print("adViewDidReceiveAd")
    }
    
    public func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) {
        print("adView - didFailToReceiveAdWithError")
        MobClick.event("google_ad_fail")
    }
    
    public func adViewWillDismissScreen(_ bannerView: GADBannerView) {
        print("adViewWillDismissScreen")
    }
    
    public func adViewWillPresentScreen(_ bannerView: GADBannerView) {
        print("adViewWillPresentScreen")
        MobClick.event("google_ad_success")
    }
    
    // MARK: GADRewardedAdDelegate
    public func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarn reward: GADAdReward) {
        print("Reward received with currency: \(reward.type), amount \(reward.amount).")
    }
    
    public func rewardedAdDidPresent(_ rewardedAd: GADRewardedAd) {
        print("Rewarded ad presented.")
        MobClick.event("google_ad_success")
    }
    
    public func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
        print("Rewarded ad dismissed.")
    }
    
    public func rewardedAd(_ rewardedAd: GADRewardedAd, didFailToPresentWithError error: Error) {
        print("Rewarded ad didFailToPresentWithError.")
        MobClick.event("google_ad_fail")
    }
}

// MARK: -- EbookBaseController 谷歌的广告代理
// MARK: GADRewardedAdDelegate
extension EbookBaseController:GADRewardedAdDelegate,GADInterstitialDelegate {
    public func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarn reward: GADAdReward) {
        print("Reward received with currency: \(reward.type), amount \(reward.amount).")
    }
    
    public func rewardedAdDidPresent(_ rewardedAd: GADRewardedAd) {
        print("Rewarded ad presented.")
        MobClick.event("google_ad_success")
        EBookDefault.setInteger(0, downCount)
    }
    
    public func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
        print("Rewarded ad dismissed.")
    }
    
    public func rewardedAd(_ rewardedAd: GADRewardedAd, didFailToPresentWithError error: Error) {
        print("Rewarded ad didFailToPresentWithError.")
        MobClick.event("google_ad_fail")
        // 如果失败，走插页广告
        createRewardAD()
    }
    
    public func interstitialDidReceiveAd(_ ad: GADInterstitial) {
        print("interstitialDidReceiveAd")
        MobClick.event("google_ad_success")
    }
    
    public func interstitial(_ ad: GADInterstitial, didFailToReceiveAdWithError error: GADRequestError) {
        print("interstitialDidDismissScreen")
        MobClick.event("google_ad_fail")
    }
    
    public func interstitialDidDismissScreen(_ ad: GADInterstitial) {
        print("adViewDidReceiveAd")
    }
    
    public func interstitialWillPresentScreen(_ ad: GADInterstitial) {
        print("interstitialWillPresentScreen")
        MobClick.event("google_ad_success")
        EBookDefault.setInteger(0, downCount)
    }
}
